package com.dp.service.impl3;

import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dp.pojo.GroupCatalogVo;
import com.dp.pub.SysProperty;
import com.dp.util.BaseBean;
import com.dp.util.InterUtil;
import com.dp.util.KeyGenerator;
import com.dp.vo.NewsCatlog;
import com.dp.vo.NewsExtendsFirstchannel;
import com.dp.vo.NewsExtendsFirstchannelButtons;
import com.dp.vo.NewsExtendsFirstchannelButtonsPK;
import com.dp.vo.TChannels;

@Service
@Transactional
public class CatalogServiceImpl3 extends BaseImpl {

	
	public boolean createOldCatalog(int channeltype,String catalogName, String channelid){
		
//		TChannels channels =getChannel(buttonid);
		// insert news_catalog
		NewsCatlog newcatalog = new NewsCatlog();
		newcatalog.setCatlogname(catalogName);
		newcatalog.setCatlogversion(getMaxCatalogVersion()+1);
		newcatalog.setCatlogcarrer("1");
		newcatalog.setIsnowpublish(0);
		newcatalog.setCreatetime(new Date());
		Set<NewsExtendsFirstchannel> newsExtendsFirstchannelSet = new HashSet();
		NewsExtendsFirstchannel nef = (NewsExtendsFirstchannel) this.get(NewsExtendsFirstchannel.class, Integer.valueOf(channelid));
		newsExtendsFirstchannelSet.add(nef);
		newcatalog.setNewsExtendsFirstchannelSet(newsExtendsFirstchannelSet);
		this.persist(newcatalog);
		Set<NewsCatlog> newsCatlogSet = new HashSet();
		newsCatlogSet.add(newcatalog);
		nef.setNewsCatlogSet(newsCatlogSet);
		this.persist(nef);
		return true;
	}

	public Long getAllVersionCount(String catalogname){
		Long count = 0L;
		List catvlist = new ArrayList();
		String hql = "SELECT n FROM NewsCatlog n ";
		if (!"".equals(catalogname) && null !=catalogname){
			hql+=" WHERE n.catlogname LIKE '%"+catalogname.trim().toLowerCase()+"%'";
		}
		hql+="order by case when n.isnowpublish=1 then 1 end desc,case when n.isnowpublish=2 then 1 end desc,n.isnowpublish desc, n.catlogversion desc, n.createtime desc ";
		List list = getQueryList(hql);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			
			NewsCatlog nc = (NewsCatlog) iterator.next();
			String sql = "SELECT  ng.groupruleid FROM news_group_catlog ngc,news_group ng WHERE ngc.groupruleid = ng.groupruleid AND ngc.catlogid="+nc.getCatlogid();
			List grouplist = this.getNativeQuery(sql);
			if (grouplist != null && grouplist.size() >0){
				count +=grouplist.size();
			}else{
				count +=1;
			}
		}
		return count;
		
	}
	public Long getAllVersionCount(String catalogname,String groupname){
		Long count = 0L;
		List catvlist = new ArrayList();
		String hql = "SELECT n FROM NewsCatlog n ";
		if (!"".equals(catalogname) && null !=catalogname){
			hql+=" WHERE n.catlogname LIKE '%"+catalogname.trim().toLowerCase()+"%'";
		}
		hql+="order by case when n.isnowpublish=1 then 1 end desc,case when n.isnowpublish=2 then 1 end desc,n.isnowpublish desc, n.catlogversion desc, n.createtime desc ";
		List list = getQueryList(hql);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			
			NewsCatlog nc = (NewsCatlog) iterator.next();
			
			String sql = "SELECT ng.groupruleid FROM news_group_catlog ngc,news_group ng WHERE ngc.groupruleid = ng.groupruleid AND ngc.catlogid="+nc.getCatlogid();
			if (!"".equals(groupname) && null !=groupname){
				sql+=" AND ng.grouprulename LIKE '%"+groupname.trim().toLowerCase()+"%'";
			}
			List grouplist = this.getNativeQuery(sql);
			if (grouplist != null && grouplist.size() >0){
				count +=grouplist.size();
			}else{
				count +=1;
			}
		}
		return count;
		
	}
	public List getAllVersionContent(String catalogname,String groupname, int firstrow, int maxrow){
		List catvlist = new ArrayList();
		String sql = "SELECT nc.catlogid,nc.catlogname,nc.catlogversion,nc.isnowpublish, ng.groupruleid,ng.grouprulename,ng.grouptype " +
				"FROM news_catlog nc LEFT JOIN news_group_catlog ngc ON nc.catlogid = ngc.catlogid LEFT JOIN news_group ng " +
				"ON ng.groupruleid = ngc.groupruleid WHERE  1=1 ";
		if (!"".equals(catalogname) && null !=catalogname){
			sql+=" AND nc.catlogname LIKE '%"+catalogname.trim()+"%'";
		}
		if (!"".equals(groupname) && null !=groupname){
			sql+=" AND ng.grouprulename LIKE '%"+groupname.trim()+"%'";
		}
		sql+="order by case when nc.isnowpublish=1 then 1 end desc,case when nc.isnowpublish=2 then 1 end desc,nc.isnowpublish desc, nc.catlogversion desc, nc.createtime desc";
		List grouplist = this.getNativeQuery(sql,firstrow, maxrow);
		if (grouplist.size() >0){
			for (Iterator iterator2 = grouplist.iterator(); iterator2.hasNext();) {
				Object[] object = (Object[]) iterator2.next();
				GroupCatalogVo groupCatalog_temp =new GroupCatalogVo();
				groupCatalog_temp.setCatlogid((Integer)object[0]);
				groupCatalog_temp.setCatlogname((String)object[1]);
				groupCatalog_temp.setCatlogversion((Integer)object[2]);
				groupCatalog_temp.setIsnowpublish((Integer)object[3]);
				groupCatalog_temp.setGroupid((Integer) object[4]);
				groupCatalog_temp.setGroupname((String) object[5]);
				groupCatalog_temp.setGrouptype((Integer) object[6]);
				catvlist.add(groupCatalog_temp);
			}
		}
		return catvlist;
		
	}
	
	public boolean createCatalog(int channeltype,String catalogName, String selectbuttons){
		try {
			//insert t_channels
			TChannels channels = new TChannels();
			String channel_id = BaseBean.ObjectToString(KeyGenerator.getInstance().getNextKeyValue("t_channels"));
			//this.updateHql("update MainKey mk set mk.keyValue= '"+channel_id.split("_")[1]+"' where mk.keyName='t_channels'");
			channels.setChannelId(channel_id);
			channels.setChannelName(catalogName);
			channels.setFunctionName("FIRST");
			channels.setCreatedDate(new Date());
			channels.setLevel("0");
			channels.setPreviousId(channel_id);
			channels.setPrimalId(channel_id);
			this.persist(channels);
			
			
			// insert news_catalog
			NewsCatlog newcatalog = new NewsCatlog();
			newcatalog.setCatlogname(catalogName);
			newcatalog.setCatlogversion(getMaxCatalogVersion()+1);
			newcatalog.setCatlogcarrer("1");
			//newcatalog.setIsnowpublish(2);
			newcatalog.setIsnowpublish(0);
			newcatalog.setCreatetime(new Date());
			this.persist(newcatalog);

			//insert news_catlog_channel
			//insert news_extends_firstchannel
			NewsExtendsFirstchannel nef = new NewsExtendsFirstchannel();
			
			nef.setChannelId(channels);
			nef.setChanneltype(channeltype);
			nef.setLastupdate(new Date());
			Set<NewsCatlog> newsCatlogSet = new HashSet();
			newsCatlogSet.add(newcatalog);
			nef.setNewsCatlogSet(newsCatlogSet);
			this.persist(nef);
			//insert news_extends_firstchannel_buttons
			
			String buttonlist = selectbuttons;
	        if(buttonlist!=null && !buttonlist.equals(""))
	        {
		    	String[] c_id_strList=buttonlist.split(",");
		    	for(int i=0;i<c_id_strList.length;i++)
		        {
		            String bid = c_id_strList[i];
		            NewsExtendsFirstchannelButtons nfb = new NewsExtendsFirstchannelButtons();
		            NewsExtendsFirstchannelButtonsPK nfbpk = new NewsExtendsFirstchannelButtonsPK(nef.getChannelid(),Integer.valueOf(bid));
		            nfb.setNewsExtendsFirstchannelButtonsPK(nfbpk);
		            nfb.setButtonorder(i+1);
		            this.persist(nfb);
		        }
	        }
	        this.em.flush();
	        return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
			// TODO: handle exception
		}
		
		
	}
	public NewsExtendsFirstchannel getNewsExtendsFirstchannelbuCatalogid(int catalogid){
		if(catalogid <=0) return null;
		NewsCatlog newcatalog =(NewsCatlog) this.get(NewsCatlog.class, catalogid);
		if(null ==newcatalog){
			return null;
		}
		boolean ischannel= newcatalog.getNewsExtendsFirstchannelSet().isEmpty();
		if(ischannel){
			return null;
		}
		NewsExtendsFirstchannel nefc =  newcatalog.getNewsExtendsFirstchannelSet().iterator().next();
		return nefc;
	}
	public List getButtonsbyCatalog(int catalogid){
		
		NewsExtendsFirstchannel nefc =  getNewsExtendsFirstchannelbuCatalogid(catalogid);
		//List newcatalog.getNewsExtendsFirstchannelSet().size();
		if(null == nefc) return null;
		String hql = "SELECT nb FROM NewsButtons nb, NewsExtendsFirstchannelButtons nefb where" +
				" nefb.newsButtons.buttonid = nb.buttonid and nefb.newsExtendsFirstchannelButtonsPK.channelid="+nefc.getChannelid()+" order by nefb.buttonorder";
		List buttonlist = getQueryList(hql);
		
		if(null ==buttonlist && buttonlist.size() <=0){
			return null;
		}
		return buttonlist;
		
	}
	
	@SuppressWarnings("unchecked")
	public boolean delCatalog(Integer catalogid){

			NewsCatlog newcatalog =(NewsCatlog) this.get(NewsCatlog.class, catalogid);
			if(null ==newcatalog){
				return false;
			}
			String hql = "SELECT n.channelid FROM news_catlog_channel n where n.catlogid="+catalogid;
			List listcatlogChannel =this.getNativeQuery(hql);
			if(null ==listcatlogChannel && listcatlogChannel.size() <=0){
				return false;
			}
//			Object catlogChannel = listcatlogChannel.get(0);
//			NewsCatlogChannel catlogChannel = (NewsCatlogChannel) listcatlogChannel.get(0);
			Integer channelid = (Integer)listcatlogChannel.get(0);
			NewsExtendsFirstchannel nef = 	(NewsExtendsFirstchannel) this.get(NewsExtendsFirstchannel.class,channelid );
			if(null ==nef){
				return false;
			}
			String buttonshql = "Delete FROM NewsExtendsFirstchannelButtons n where n.newsExtendsFirstchannelButtonsPK.channelid="+channelid;
			this.updateHql(buttonshql);
			this.remove(newcatalog);
			String delhql = "Delete FROM news_catlog_channel  where catlogid="+catalogid;
			this.updateNativeQuery(delhql);
			String channelshql = "Delete FROM t_channels where channel_id='"+nef.getChannelId().getChannelId()+"'";
			this.updateNativeQuery(channelshql);
			
			this.remove(nef);
	        return true;
		
	}
	public List getAllButtons(){
		String hql = "SELECT n FROM NewsButtons n where n.buttontype not in(1,2,4,5)";
		//3导航文本6超链接7我的收藏8发送邮件9我的杂志11分享菜单……
		List buttonlist = getQueryList(hql);
		return buttonlist;
		
	}
	
	public Integer getMaxCatalogVersion(){
		String hql = "SELECT max(n.catlogversion) FROM NewsCatlog n";
//		List list = getQueryList(hql);
		Object version = getSingleResult(hql);
		int maxversion =1;
		if(version !=null){
			maxversion=(Integer) version;
		} 
		return maxversion;
	}
	
	/*public List getAllVersion(){
		
		String hql = "SELECT n FROM NewsCatlog n order by n.isnowpublish, n.catlogversion desc, n.createtime desc ";
		List buttonlist = getQueryList(hql);
		return buttonlist;
		
	}*/
	
	/**
	 * catlog平台
	 * @return
	 */
    /*public List getAllVersion2(){
		
		String hql = "SELECT n FROM NewsCatlog n where isnowpublish!=1 order by n.isnowpublish, n.catlogversion desc, n.createtime desc ";
		List buttonlist = getQueryList(hql);
		return buttonlist;
		
	}*/
	/*public Long getAllVersionCount(){
		
		String hql = "SELECT count(n) FROM NewsCatlog n order by n.isnowpublish desc, n.catlogversion desc, n.createtime desc ";
		Long count = (Long) getSingleResult(hql);
		return count;
		
	}*/
	
	/*public List getAllVersionCount(int firstrow, int maxrow){
		List catvlist = new ArrayList();
		String hql = "SELECT n FROM NewsCatlog n order by case when n.isnowpublish=1 then 1 end desc,case when n.isnowpublish=2 then 1 end desc,n.isnowpublish desc, n.catlogversion desc, n.createtime desc ";
		List list = getQueryList(hql, firstrow, maxrow);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			
			NewsCatlog nc = (NewsCatlog) iterator.next();
			Set ncpset = nc.getNewsCatlogPlatformSet();
			if (null !=ncpset && ncpset.size() >0){
				for (Iterator iterator2 = ncpset.iterator(); iterator2.hasNext();) {

					NewsCatlogPlatform ncp = (NewsCatlogPlatform) iterator2.next();
					CatalogVersion catalogVersion = new CatalogVersion();
					catalogVersion.setCatlogid(nc.getCatlogid());
					catalogVersion.setAuiter(nc.getAuiter());
					catalogVersion.setCatlogcarrer(nc.getCatlogcarrer());
					catalogVersion.setCatlogname(nc.getCatlogname());
					catalogVersion.setCatlogversion(nc.getCatlogversion());
					catalogVersion.setCreater(nc.getCreater());
					catalogVersion.setCreatetime(nc.getCreatetime());
					catalogVersion.setFirstpageid(nc.getFirstpageid());
					catalogVersion.setIsnowpublish(nc.getIsnowpublish());
					catalogVersion.setMagent(ncp.getNewsCatlogPlatformPK().getMagent());
					catalogVersion.setMlocale(ncp.getNewsCatlogPlatformPK().getMlocale());
					catalogVersion.setMplatform(ncp.getNewsCatlogPlatformPK().getMplatform());
					catalogVersion.setMserialnum(ncp.getNewsCatlogPlatformPK().getMserialnum());
					catvlist.add(catalogVersion);
				}
			}else{
				CatalogVersion catalogVersion = new CatalogVersion();
				catalogVersion.setCatlogid(nc.getCatlogid());
				catalogVersion.setAuiter(nc.getAuiter());
				catalogVersion.setCatlogcarrer(nc.getCatlogcarrer());
				catalogVersion.setCatlogname(nc.getCatlogname());
				catalogVersion.setCatlogversion(nc.getCatlogversion());
				catalogVersion.setCreater(nc.getCreater());
				catalogVersion.setCreatetime(nc.getCreatetime());
				catalogVersion.setFirstpageid(nc.getFirstpageid());
				catalogVersion.setIsnowpublish(nc.getIsnowpublish());
				catvlist.add(catalogVersion);
			}
			
		}
		return catvlist;
		
	}*/
	
	public void rePublish(int catalog){
		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalog);
		catlog.setIsnowpublish(2);
		catlog.setCatlogversion(getMaxCatalogVersion()+1);
		this.save(catlog);
	}
	
	
	/**
	 * 定时器刷新缓存publishcatlog时调用
	 */
	/*public void rePublishcatlogURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
    	    //url=System.getProperty("flushportalurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     	
            url+="action/server!publishcatlog.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
            	  } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
                  
        }
      
	 }
	*/
	/**
	 * 刷新缓存publishcatlog
	 * 设置默认目录，更改多平台信息时调用
	 */
	public void rePublishAllcatlogURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     	
            url+="action/server!publishallcatlog.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
            	  } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
                  
        }
      
	 }
	
	/**
	 * 刷新缓存publishcatlog
	 * 目录发布时调用
	 */
	public void rePublishcatlogURL(int catlogid){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     	
            url+="action/server!publishcatlog.do?catlogid="+catlogid;
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
            	  } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
                  
        }
      
	 }
	/**
	 * 刷新缓存publishtitle时
	 * 5分钟立即发布频道定时器和3点，17点更新频道缓存定时器调用
	 */
	/*public void rePublishtitleURL(String channelidlist){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/server!publishtitle.do?channelidlist="+channelidlist;
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }*/
	
	/**
	 * 加载缓存reloadWeather时调用
	 */
	/*public void reloadWeatherURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/server!reloadWeather.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }*/
	/**
	 * 加载新的系统参数到缓存时调用:reloadsysparam
	 */
	/*public void reloadSysparamURL(){
	    String url="";
	    for(int i=1;i<1000;i++)
        {
            url=SysProperty.getPrep("sysserverurl."+i);
            if(url==null||"".equals(url)){
            	break;  
            }     
            url+="action/server!reloadsysparam.do";
            	 try{
                     URL testUrl = new URL(url);
                     HttpURLConnection conn = (HttpURLConnection) testUrl.openConnection();
   			      conn.setRequestMethod("POST");
   				  int ret = conn.getResponseCode();
   				  conn.disconnect();
                     log.info(ret != 200?InterUtil.rb.getString("src.refPorErr")+"："+url:InterUtil.rb.getString("src.refPorSuc")+"："+url);
   		         } catch (Exception e) {	log.error(InterUtil.rb.getString("src.refPorErr")+"："+url+",Connection refused: connect");}	    		
           
        }
      
	 }*/
	/*public TChannels getChannel(String buttonid){
		String hql = "select tc from NewsButtons nb,TChannels tc where nb.buttontext = tc.channelName and nb.buttonid='"+buttonid+"'";
		TChannels channel = (TChannels) getSingleResult(hql);
		return channel;
		
	}*/
	
	public List getFirstChannels(){
		String hql = "select new com.dp.pojo.FirstChannels(tc.channelId, nef.channelid,"+
			"tc.serviceCode, tc.channelName, tc.functionName,tc.status, tc.ordered) from TChannels tc, NewsExtendsFirstchannel nef where tc.channelId = nef.channelId and nef.channelid is not null";
		List channellist = getQueryList(hql);
		return channellist;
		
	}
	
//	public List getCatalogView(String channelid){
//		String hql = "SELECT new com.dp.pojo.CatalogView(nef.channel_id, nfb.buttonid,nb.buttonname,nct.channelid)  FROM NewsExtendsFirstchannel nef,NewsExtendsFirstchannelButtons nfb,NewsButtons nb, "+
//					"NewsContenttype nct WHERE nef.channelid='12' AND nef.channelid = nfb.channelid "+
//					"AND nfb.buttonid = nb.buttonid AND nb.buttoncontenttype = nct.newscontenttype ";
//		List channellist = getQueryList(hql);
//		return channellist;
//		
//	}
//	
//	public List getLastCatalogView(String channelid){
//		String hql = "SELECT new com.dp.pojo.CatalogView(nef.channel_id, nfb.buttonid,nb.buttonname,nct.channelid)  FROM NewsExtendsFirstchannel nef,NewsExtendsFirstchannelButtons nfb,NewsButtons nb, "+
//					"NewsContenttype nct WHERE nef.channelid='12' AND nef.channelid = nfb.channelid "+
//					"AND nfb.buttonid = nb.buttonid AND nb.buttoncontenttype = nct.newscontenttype ";
//		List channellist = getQueryList(hql);
//		return channellist;
//		
//	}


	/**
	 * 目录下线
	 * @param catalogid
	 */
	public void Offline(int catalogid) {
		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalogid);
		catlog.setIsnowpublish(3);
		this.save(catlog);
	}
	
	/**
	 * 是否为默认目录
	 * @param catalogid
	 */
	public boolean isDefaulted(int catalogid) {
		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalogid);
		if(catlog.getIsnowpublish()==1){
			//默认再发布
			catlog.setCatlogversion(getMaxCatalogVersion()+1);
			this.save(catlog);
			return true;
		}
		return false;
	}
	
	/**
	 * 设为默认目录
	 * @param catalogid
	 */
	public void SetDefaulted(int catalogid) {
		String hql = "update NewsCatlog n set n.isnowpublish=0 where n.isnowpublish=1";
		updateHql(hql);
		NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catalogid);
		catlog.setIsnowpublish(1);
		catlog.setCatlogversion(getMaxCatalogVersion()+1);
		this.save(catlog);
	}

//	/**
//	 * 平台未关联catlog且catlog状态为发布，则修改为下线
//	 */
//	public void updateCatlogOfflined(Integer catlogid) {
//		String hql = "select ncp from NewsCatlogPlatform ncp where ncp.catlogid.catlogid="+catlogid;
//		List list = getQueryList(hql);
//		if(list.size()>0){
//			return ;
//		}
//		hql = "select nc.isnowpublish from NewsCatlog nc where nc.catlogid="+catlogid;
//		Object obj = getSingleResult(hql);
//		int isnowpublish =0;
//		if(obj !=null){
//			isnowpublish=(Integer) obj;
//		} 
//		//为发布状态，设置为下线状态3
//		if(isnowpublish==2){
//			NewsCatlog catlog = (NewsCatlog) this.get(NewsCatlog.class, catlogid);
//			catlog.setIsnowpublish(3);
//			this.save(catlog);
//		}
//		
//	}
	
	public boolean isAssociatedGroup(int catalogid) {
		String sql = "SELECT groupruleid FROM news_group_catlog  WHERE catlogid="+catalogid;
		List grouplist = this.getNativeQuery(sql);
		if(null != grouplist && grouplist.size() > 0){
			return true;
		}else{
			return false;
		}
		
	}

	public void deleteGroup(int catalogid) {
		// TODO Auto-generated method stub
		String sql = "delete FROM news_group_catlog  WHERE catlogid="+catalogid;
		this.updateNativeQuery(sql);
	}
	
	public boolean sortbuttons(int catalogid, String selectbuttons) {
		/*String buttonlist = selectbuttons;
		Boolean resultb=true;
		try {
			if(buttonlist!=null && !buttonlist.equals(""))
	        {
	        	this.init();
	        	NewsExtendsFirstchannel nefc =  getNewsExtendsFirstchannelbuCatalogid(catalogid);
	    		
	        	this.sql = "update news_extends_firstchannel_buttons  set buttonorder=? where channelid=? and buttonid=?";
				this.prep=this.conn.prepareStatement(sql);
		    	String[] c_id_strList=buttonlist.split(",");
		    	for(int i=0;i<c_id_strList.length;i++)
		        {
		    		int buttonid = Integer.parseInt(c_id_strList [i]) ;
					prep.setInt(1, i+1);
					prep.setInt(2, nefc.getChannelid());
					prep.setInt(3, buttonid);
					prep.addBatch();
		        }
		    	prep.executeBatch();
		    	conn.commit(); 
		    	resultb= true;
	        }
		} catch (Exception e) {
			logger.info("sortbuttons fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
			if(conn!=null){
				try {
					conn.rollback();
				} catch (SQLException e1) {
					e1.printStackTrace();
				} 
			}
		}finally{
			this.closeAll();
		}
		return resultb;*/
		
		String buttonlist = selectbuttons;
		Boolean resultb=true;
		try {
			if(buttonlist!=null && !buttonlist.equals(""))
	        {
	        	NewsExtendsFirstchannel nefc =  getNewsExtendsFirstchannelbuCatalogid(catalogid);
	    		
	        	this.sql = "update news_extends_firstchannel_buttons  set buttonorder=? where channelid=? and buttonid=?";
	        	Query query=em.createNativeQuery(sql);
		    	String[] c_id_strList=buttonlist.split(",");
		    	for(int i=0;i<c_id_strList.length;i++)
		        {
		    		int buttonid = Integer.parseInt(c_id_strList [i]) ;
		    		query.setParameter(1, i+1);
		    		query.setParameter(2, nefc.getChannelid());
		    		query.setParameter(3, buttonid);
		    		query.executeUpdate();
		        }
		    	resultb= true;
	        }
		} catch (Exception e) {
			logger.info("sortbuttons fail !!!" + e.getMessage());
			e.printStackTrace();
			resultb=false;
		}
		return resultb;
	}

}
